<?php

namespace App\Service\queue;

use App\Job\DyCouponJob;
use App\Model\Applet;
use App\Service\CommicService;
use GuzzleHttp\Client;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\AsyncQueue\Driver\DriverInterface;
class DyCouponService extends CommicService
{
    protected DriverInterface $driver;

    //获取token
    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";
    //创建优惠券
    public static $createUrl = "https://open.douyin.com/api/promotion/v1/coupon/create_coupon_meta";
    //创建营销活动
    public static $createPromotionActivityUrl = "https://open.douyin.com/api/promotion/v2/activity/create_promotion_activity/";
    //修改营销活动
    public static $updatePromotionActivityUrl = "https://open.douyin.com/api/promotion/v2/activity/modify_promotion_activity/";
    //修改优惠券
    public static $updateUrl = "https://open.douyin.com/api/promotion/v1/coupon/update_coupon_meta_param";

    public static $selectUrl = 'https://open.douyin.com/api/promotion/v1/coupon/get_coupon_meta/';

    //删除优惠券
    public static $deleteUrl = "https://open.douyin.com/api/promotion/v1/coupon/delete_coupon_meta";
    //修改库存
    public static $metaStockUrl = "https://open.douyin.com/api/promotion/v1/coupon/update_coupon_meta_stock/";
    //修改小程序券状态
    public static $metaStatusUrl = "https://open.douyin.com/api/promotion/v1/coupon/update_coupon_meta_status";
    //修改营销模式状态
    public static $activityStatusUrl = "https://open.douyin.com/api/promotion/v2/activity/update_promotion_activity_status/";

    public function __construct(DriverFactory $driverFactory)
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
        $this->logger = $container->get(LoggerFactory::class)->get('log', 'dycoupon');
        $this->driver = $driverFactory->get('default');
    }
    /**
     * 创建优惠券
     */
    public function createCoupon($appletCouponInfo,$app_id){
        $returnResult = array();
        try {
            $this->logger->info('开始处理抖音券的创建逻辑');
            $accessToken = $this->getDyAccessToken($appletCouponInfo->applet_id);

            $params         = [
                "app_id"   =>$app_id,
                "merchant_meta_no"   => (string)$appletCouponInfo->id,
                "name"   => $appletCouponInfo->name,
                "discount_type"   => $appletCouponInfo->discount_type,
                "receive_begin_time"   => strtotime($appletCouponInfo->receive_begin_time),
                "receive_end_time"   => strtotime($appletCouponInfo->receive_end_time),
                "valid_type"   => $appletCouponInfo->valid_type,
                "valid_duration"   => $appletCouponInfo->valid_duration* 24 * 60 * 60,
                "consume_path"   =>'pages/tabBar/square/square?scene=coupon',
                "callback_url"   => 'https://kydy.kuaiyingbox.com/dy_coupon/callback',
                "send_scene"    => 2,
                "stock_number"   => $appletCouponInfo->stock_number,
                "consume_desc"   => $appletCouponInfo->consume_desc,
                "receive_desc"   => $appletCouponInfo->receive_desc,
                "send_desc"   => $appletCouponInfo->send_desc,
            ];
            $url = self::$createUrl;
            $this->logger->info('请求创建小程序券数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求创建小程序券Url：'.$url);
            $postResult  = $this->request($params, $url,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('调用创建小程序券接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                $returnResult =  $postResult;
            }else {
                $this->logger->error('调用创建小程序券接口失败 返回数据：' . PHP_EOL . var_export(['result' => $postResult], true));
                $returnResult = $postResult;
            }
        }catch (\Exception $e){
            $returnResult['err_no'] = 0;
            $returnResult['err_msg'] = $e->getMessage().'|'.$e->getLine();
        }


        return $returnResult;
    }
    /**
     * 修改优惠券
     */
    public function updateCoupon($appletCouponInfo,$app_id){
        $returnResult = array();
        try {
            $this->logger->info('开始处理抖音券的修改逻辑');
            $accessToken = $this->getDyAccessToken($appletCouponInfo->applet_id);

            $params         = [
                "coupon_meta_id"   => (string)$appletCouponInfo->coupon_meta_id,
                "name"   => $appletCouponInfo->name,
                "receive_begin_time"   => strtotime($appletCouponInfo->receive_begin_time),
                "receive_end_time"   => strtotime($appletCouponInfo->receive_end_time),
                "consume_desc"   => $appletCouponInfo->consume_desc,
                "receive_desc"   => $appletCouponInfo->receive_desc,
                "send_desc"   => $appletCouponInfo->send_desc,
            ];
            $url = self::$updateUrl;
            $this->logger->info('请求修改小程序券数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求修改小程序券Url：'.$url);
            $postResult  = $this->request($params, $url,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('调用修改小程序券接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                $returnResult =  $postResult;
            }else {
                $this->logger->error('调用修改小程序券接口失败 返回数据：' . PHP_EOL . var_export(['result' => $postResult], true));
                $returnResult = $postResult;
            }
        }catch (\Exception $e){
            $returnResult['err_no'] = 0;
            $returnResult['err_msg'] = $e->getMessage().'|'.$e->getLine();
        }


        return $returnResult;
    }
    /**
     * 删除优惠券
     */
    public function deleteCoupon($appletCouponInfo){
        $returnResult = array();
        try {
            $this->logger->info('开始处理抖音券的删除逻辑');
            $accessToken = $this->getDyAccessToken($appletCouponInfo->applet_id);

            $params         = [
                "coupon_meta_id"   => (string)$appletCouponInfo->coupon_meta_id,
                "app_id"   => $appletCouponInfo->app_id,
            ];
            $url = self::$deleteUrl;
            $this->logger->info('请求删除小程序券数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求删除小程序券Url：'.$url);
            $postResult  = $this->request($params, $url,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('调用删除小程序券接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                $returnResult =  $postResult;
            }else {
                $this->logger->error('调用删除小程序券接口失败 返回数据：' . PHP_EOL . var_export(['result' => $postResult], true));
                $returnResult = $postResult;
            }
        }catch (\Exception $e){
            $returnResult['err_no'] = 0;
            $returnResult['err_msg'] = $e->getMessage().'|'.$e->getLine();
        }


        return $returnResult;
    }
    /**
     * 修改库存 只支持加库存，不支持减少库存
     */
    public function updateMetaStock($appletCouponInfo,$number){

        $returnResult = array();
        try {
            $this->logger->info('开始处理抖音券的修改库存');
            $accessToken = $this->getDyAccessToken($appletCouponInfo->applet_id);

            $params         = [
                "coupon_meta_id"   => (string)$appletCouponInfo->coupon_meta_id,
                "app_id"   => $appletCouponInfo->app_id,
                "action"   => 'increase',
                "number"   =>$number,
                "unique_key"   => (string)(time()+$number),
            ];
            $url = self::$metaStockUrl;
            $this->logger->info('请求修改小程序券库存数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求修改小程序券库存Url：'.$url);
            $postResult  = $this->request($params, $url,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('调用修改小程序券库存接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                $returnResult =  $postResult;
            }else {
                $this->logger->error('调用修改小程序券库存接口失败 返回数据：' . PHP_EOL . var_export(['result' => $postResult], true));
                $returnResult = $postResult;
            }
        }catch (\Exception $e){
            $returnResult['err_no'] = 0;
            $returnResult['err_msg'] = $e->getMessage().'|'.$e->getLine();
        }


        return $returnResult;
    }

    public function selectCoupon($appletCouponInfo){

        $accessToken = $this->getDyAccessToken($appletCouponInfo->applet_id);
        $params         = [
            "coupon_meta_id"   => (string)$appletCouponInfo->coupon_meta_id,
            "app_id"   => $appletCouponInfo->app_id,
        ];
        $url = self::$selectUrl;
        $postResult  = $this->request($params, $url,'POST',$accessToken);
        return $postResult;
    }

    /**
     * 修改库存 只支持加库存，不支持减少库存
     */
    public function updateMetaStatus($appletCouponInfo,$coupon_meta_status){

        $returnResult = array();
        try {
            $this->logger->info('开始处理抖音券的修改状态');
            $accessToken = $this->getDyAccessToken($appletCouponInfo->applet_id);

            $params         = [
                "coupon_meta_id"   => (string)$appletCouponInfo->coupon_meta_id,
                "app_id"   => $appletCouponInfo->app_id,
                "coupon_meta_status"   => $coupon_meta_status
            ];
            $url = self::$metaStatusUrl;
            $this->logger->info('请求修改小程序券修改状态：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求修改小程序券修改状态Url：'.$url);
            $postResult  = $this->request($params, $url,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('请求修改小程序券修改状态接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                $returnResult =  $postResult;
            }else {
                $this->logger->error('请求修改小程序券修改状态接口失败 返回数据：' . PHP_EOL . var_export(['result' => $postResult], true));
                $returnResult = $postResult;
            }
        }catch (\Exception $e){
            $returnResult['err_no'] = 0;
            $returnResult['err_msg'] = $e->getMessage().'|'.$e->getLine();
        }


        return $returnResult;
    }


    /**
     * 创建营销活动
     */
    public function createPromotionActivity($appletCouponPromotionActivityInfo,$app_id,$coupon_meta_id){
        $returnResult = array();
        try {
            $this->logger->info('开始处理抖音券的创建逻辑');
            $accessToken = $this->getDyAccessToken($appletCouponPromotionActivityInfo->applet_id);

            $params         = [
                "promotion_activity" =>[
                    "activity_name"   =>$appletCouponPromotionActivityInfo->activity_name,
                    "coupon_meta_id"    => $coupon_meta_id,
                    "receive_limit" => $appletCouponPromotionActivityInfo->receive_limit,
                    "send_scene" => 5,
                    "sidebar_activity" =>[
                        "action_trigger" => $appletCouponPromotionActivityInfo->action_trigger,
                        "high_value_content" => $appletCouponPromotionActivityInfo->high_value_content,
                        "jump_text" => $appletCouponPromotionActivityInfo->jump_text,
                        "recent_bubble_text" =>$appletCouponPromotionActivityInfo->recent_bubble_text,
                        "short_title" => $appletCouponPromotionActivityInfo->short_title,
                        "valid_begin_time"   => strtotime($appletCouponPromotionActivityInfo->valid_begin_time),
                        "valid_end_time"   => strtotime($appletCouponPromotionActivityInfo->valid_end_time),
                        "need_bind" =>false
                    ],
                ]
            ];
            $url = self::$createPromotionActivityUrl;
            $this->logger->info('请求创建营销活动数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求创建营销活动Url：'.$url);
            $postResult  = $this->request($params, $url,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('调用创建营销活动接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                $returnResult =  $postResult;
            }else {
                $this->logger->error('调用创建营销活动接口失败 返回数据：' . PHP_EOL . var_export(['result' => $postResult], true));
                $returnResult = $postResult;
            }
        }catch (\Exception $e){
            $returnResult['err_no'] = 0;
            $returnResult['err_msg'] = $e->getMessage().'|'.$e->getLine();
        }


        return $returnResult;
    }
    /**
     * 创建营销活动
     */
    public function updatePromotionActivity($appletCouponPromotionActivityInfo,$app_id){
        $returnResult = array();
        try {
            $this->logger->info('开始处理抖音券的修改逻辑');
            $accessToken = $this->getDyAccessToken($appletCouponPromotionActivityInfo->applet_id);

            $params         = [
                "promotion_activity" =>[
                    "activity_id"   =>$appletCouponPromotionActivityInfo->activity_id,
                    "activity_name"   =>$appletCouponPromotionActivityInfo->activity_name,
                    "receive_limit" =>$appletCouponPromotionActivityInfo->receive_limit,
                    "sidebar_activity" =>[
                        "high_value_content" => $appletCouponPromotionActivityInfo->high_value_content,
                        "jump_text" => $appletCouponPromotionActivityInfo->jump_text,
                        "recent_bubble_text" =>$appletCouponPromotionActivityInfo->recent_bubble_text,
                        "short_title" => $appletCouponPromotionActivityInfo->short_title,
                        "valid_begin_time"   => strtotime($appletCouponPromotionActivityInfo->valid_begin_time),
                        "valid_end_time"   => strtotime($appletCouponPromotionActivityInfo->valid_end_time),
                    ],
                ]
            ];
            $url = self::$updatePromotionActivityUrl;
            $this->logger->info('请求修改营销活动数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求修改营销活动Url：'.$url);
            $postResult  = $this->request($params, $url,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('调用修改营销活动接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                $returnResult =  $postResult;
            }else {
                $this->logger->error('调用修改营销活动接口失败 返回数据：' . PHP_EOL . var_export(['result' => $postResult], true));
                $returnResult = $postResult;
            }
        }catch (\Exception $e){
            $returnResult['err_no'] = 0;
            $returnResult['err_msg'] = $e->getMessage().'|'.$e->getLine();
        }


        return $returnResult;
    }

    /**
     * 修改状态营销活动
     */
    public function updateActivityStatus($appletCouponPromotionActivityInfo,$status){
        $returnResult = array();
        try {
            $this->logger->info('开始处理营销活动的状态逻辑');

            $accessToken = $this->getDyAccessToken($appletCouponPromotionActivityInfo->applet_id);

            $params         = [
                "activity_id"   =>$appletCouponPromotionActivityInfo->activity_id,
                "status" => $status
            ];
            $url = self::$activityStatusUrl;
            $this->logger->info('请求修改营销活动状态数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求修改营销活动状态Url：'.$url);
            $postResult  = $this->request($params, $url,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('调用状态营销活动接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                $returnResult =  $postResult;
            }else {
                $this->logger->error('调用状态营销活动接口失败 返回数据：' . PHP_EOL . var_export(['result' => $postResult], true));
                $returnResult = $postResult;
            }
        }catch (\Exception $e){
            $returnResult['err_no'] = 0;
            $returnResult['err_msg'] = $e->getMessage().'|'.$e->getLine();
        }


        return $returnResult;
    }

    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 30
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}